package com.younion.util.config;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import com.younion.util.HtmlIOUtil;

public class ConfigHelper extends HttpServlet {
	private static HashMap configs = new HashMap();
	private static String xmlFile = "";

	public ConfigHelper() {
	}

	public void init(ServletConfig arg0) throws ServletException {
		super.init(arg0);
		this.loadConfigFromXml();
	}

	public static void loadConfigFromXml() {
		configs.clear();
		String path = File.separator + "data" + File.separator + "younion" + File.separator
				+ "config" + File.separator;
		xmlFile = path + File.separator + "younion-config.xml";
		File file = new File(xmlFile);
		if (!file.exists()) {
			xmlFile = (path == null ? "" : path) + File.separator + "younion-config.xml";
		}
		try {
			FileInputStream fIS = new FileInputStream(xmlFile);
			DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
			DocumentBuilder docB = docBF.newDocumentBuilder();
			Document doc = docB.parse(fIS);
			Element rootNode = doc.getDocumentElement();
			NodeList basePropertyList = rootNode.getChildNodes();
			Text tempText = null;
			String tempVal;
			for (int i = 0; i < basePropertyList.getLength(); i++) {
				if (basePropertyList.item(i) instanceof Element) {
					Element aNode = (Element) basePropertyList.item(i);
					if (aNode.getNodeName().equals("config")) {
						if (aNode.getAttribute("className") == null
								|| aNode.getAttribute("className").equals("")) {
							HashMap map = new HashMap();
							NodeList children = aNode.getChildNodes();
							for (int j = 0; j < children.getLength(); j++) {
								if (children.item(j) instanceof Element) {
									Element bNode = (Element) children.item(j);
									tempText = (Text) bNode.getFirstChild();
									if (tempText != null) {
										tempVal = StringUtils.trim(tempText.getNodeValue());
										map.put(bNode.getNodeName(), tempVal);
									}
								}
							}
							configs.put(aNode.getAttribute("name").toLowerCase(), map);
						} else {
							ConfigInterface ci = (ConfigInterface) Class.forName(
									aNode.getAttribute("className")).newInstance();
							ci.parse(aNode);
							configs.put(aNode.getAttribute("name").toLowerCase(), ci);
						}
					}
				}
			}
		} catch (Exception ee) {
			ee.printStackTrace();
		}
	}

	public static Object getConfig(String configName) {
		return configs.get(configName);
	}

	public static String fastGetConfig(String configName, String key) {
		Object map = configs.get(configName);
		if (map == null || !(map instanceof HashMap))
			return null;
		return (String) ((HashMap) map).get(key);
	}

	public static String fastGetConfig(String configName, String key, String defaultValue) {
		String strRet = fastGetConfig(configName, key);
		strRet = strRet == null ? defaultValue : strRet;
		return strRet;
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		StringBuffer msg = new StringBuffer();
		String action = (String) req.getParameter("action");
		ServletOutputStream servletOut = resp.getOutputStream();
		if (action.equals("reload")) {
			loadConfigFromXml();
			msg.append("重新加载成功！");
		} else if (action.equals("showxml")) {
			File file = new File(xmlFile);
			byte[] b = new byte[(int) file.length()];
			DataInputStream dis = new DataInputStream(new FileInputStream(xmlFile));
			for (int i = 0; i < file.length(); i++) {
				b[i] = dis.readByte();
			}
			msg.append(HtmlIOUtil.filterForHtml(new String(b, "gbk")));
			dis.close();
		} else if (action.equals("showconfig")) {
			ArrayList keys = new ArrayList(configs.keySet());
			for (int i = 0; i < keys.size(); i++) {
				Object config = configs.get(keys.get(i));
				msg.append("配置：" + keys.get(i) + "<br>");
				if (config instanceof HashMap) {
					ArrayList keys1 = new ArrayList(((HashMap) config).keySet());
					for (int j = 0; j < keys1.size(); j++) {
						msg.append("&nbsp;&nbsp;&nbsp;&nbsp;" + keys1.get(j) + " -- "
								+ ((HashMap) config).get(keys1.get(j)) + "<br>");
					}
				} else {
					msg.append(config.toString());
				}
				msg.append("<br>");
			}
		}
		byte[] buf = msg.toString().getBytes();
		resp.setContentLength(buf.length);
		servletOut.write(buf);
		servletOut.close();
	}

}
